package com.qianxun.entrace.resolver;


import com.qianxun.framework.common.util.ObjectUtil;
import com.qianxun.module.datasource1.common.service.EhcacheService;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.servlet.LocaleResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;
import java.util.Objects;

/**
 * 自定义国际化解析器
 * @author: huwei
 * @date:   2019/10/23 17:49
 * @version:  1.0.0
*/
public class CustomLocaleResolver implements LocaleResolver {
      
    private static final String I18N_LANGUAGE = "i18n_language";
    private static final String I18N_LANGUAGE_SESSION = "i18n_language_session";

    @Lazy
    @Resource
    private EhcacheService ehcacheService;
    
    @Override
    public Locale resolveLocale(HttpServletRequest req) {
        String i18n_language = req.getParameter(I18N_LANGUAGE);
        Locale locale = Locale.getDefault();
        if(Objects.nonNull(i18n_language)) {
            String[] language = i18n_language.split("_");
            locale = new Locale(language[0], language[1]);
            HttpSession session = req.getSession();
            String localeJsonString = ObjectUtil.toJson(locale);
            ehcacheService.putInGlobal((session.getId() + "#" + I18N_LANGUAGE_SESSION), localeJsonString);
        }else {
           HttpSession session = req.getSession();
           String localeJson = ehcacheService.getInGlobal(session.getId() + "#" + I18N_LANGUAGE_SESSION);
           Locale localeInCache = ObjectUtil.toBean(localeJson, Locale.class);
           if(Objects.nonNull(localeInCache)) {
        	   locale = localeInCache;
           }
        }  
        return locale;  
    }  
  
    @Override
    public void setLocale(HttpServletRequest req, HttpServletResponse res, Locale locale) {
          
    }  
  
}  